package com.dxf.hchat.netty;

import io.netty.channel.Channel;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 建立用户id和通道的关联
 */
public class UserChannelMap {
    private static Map<String, Channel> userHCannelMap;
    static {
         userHCannelMap = new HashMap<String, Channel>();
    }

    /**
     * 添加通道和用户关联
     * @param userId
     * @param channel
     */
    public static void   put(String userId,Channel channel){
        userHCannelMap.put(userId,channel);
    }

    /**
     * 移除静态关联
     * @param userId
     */
    public static void remove(String userId){
        userHCannelMap.remove(userId);
    }

    /**
     * 打印通过id和userId
     */
    public static void print(){
        for (String userId :userHCannelMap.keySet()){
            System.out.println("用户id-->"+userId+"|"+" 通过:--->"+userHCannelMap.get(userId).id());
        }

    }


    /**
     * 根据通道id,移除用户与通道的关联
     */
    public static void removeByChannelId(String channelId){
        if (!StringUtils.isNotBlank(channelId)){
            return;
        }


        for (String userId : userHCannelMap.keySet()) {
            Channel channel = userHCannelMap.get(userId);
            if (channelId.equals(channel.id().asLongText())){

                System.out.println("客户端连接断开,用户id:"+userId+"  通道:"+channelId);
                userHCannelMap.remove(userId);
            }
        }


    }

    /**
     * 根据userId 得到这个用户的通道(确定用户是否在线)
     * @param friendId
     * @return
     */
    public static Channel get(String friendId) {

        return userHCannelMap.get(friendId);

    }
}
